package com.bestcem.xm.txtanls.annotation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;

/**
 * 根据字符串 或者 枚举常量class 执行数据校验
 * 
 * @author : rong.zeng@idianyan.com
 * @version V1.0
 * @Description: 根据字符串 或者 枚举常量class 执行数据校验
 * @date Date : 2019年10月22日 15:24
 */
@Component
public class EnumValueValidateImpl implements ConstraintValidator<EnumValueValidate, String> {
    private Logger logger = LoggerFactory.getLogger(EnumValueValidateImpl.class);

    EnumValueValidate valueValidate;

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (!StringUtils.isEmpty(valueValidate.values())) {
            String[] value_array = valueValidate.values().split(",");
            for (int i = 0; i < value_array.length; i++) {
                // 存在一致就跳出循环
                if (value_array[i].equals(value)) {
                    return true;
                }
            }
        } else if (valueValidate.enumClass() != null) {
            try {
                Class clz = valueValidate.enumClass();
                Object[] objects = clz.getEnumConstants();
                Method getCode = clz.getMethod("getCode");
                for (Object obj : objects) {
                    String code = (String)getCode.invoke(obj);
                    if (value.equalsIgnoreCase(code)) {
                        return true;
                    }
                }
            } catch (Exception e) {
                logger.error("校验出错了:{}", e);
            }

        }
        return false;
    }

    @Override
    public void initialize(EnumValueValidate constraintAnnotation) {
        this.valueValidate = constraintAnnotation;
    }



}
